#!/bin/bash

#要创建kvm虚拟机的数量
create_kvm(){
read -p "要创建虚拟机的数量为：" num

template_qcow2=/template/template.qcow2
template_xml=/template/template.xml

for i in $(seq ${num});do

#创建差异镜像
qemu-img create -f qcow2 -b ${template_qcow2} /var/lib/libvirt/images/vm${i}_centos79.qcow2 &> /dev/null
cp ${template_xml} /etc/libvirt/qemu/vm${i}_centos79.xml

#修改配置文件内容
#修改host名，和磁盘文件名
sed -ri "s/test/vm${i}_centos79/g" /etc/libvirt/qemu/vm${i}_centos79.xml
echo 1
#修改uuid
sed -ri "s|<uuid>.*</uuid>|  <uuid>$(uuidgen)</uuid>|g" /etc/libvirt/qemu/vm${i}_centos79.xml
echo 2
#修改mac
new_mac=52:54:00:$(openssl rand -hex 10 | sed -r 's/(..)(..)(..).*/\1:\2:\3/')
echo 3
sed -ri "/52:54:00/ c\      <mac address='${new_mac}'/>" /etc/libvirt/qemu/vm${i}_centos79.xml
echo 4
#定义新建的虚拟主机
virsh define /etc/libvirt/qemu/vm${i}_centos79.xml
echo 5
#启动虚拟机
virsh start vm${i}_centos79
echo 6
done

}

delete_kvm(){

#查看现存的虚拟机
echo "现有的虚拟机"
visrh list --all

read -p "请输入要删除的虚拟机" id

virsh shutdown vm${id}_centos79
virsh undefine vm${id}_centos79
rm -rf /var/lib/libvirt/images/vm${id}_centos79.qcow2

virsh list --all
}


while true;do

cat << eof
1、创建虚拟机
2、删除虚拟机
3、查看虚拟机
4、退出
eof

read -p "请选择你的操作" id

  case ${id} in
  1)
   create_kvm
  ;;
  2)
   delete_kvm
  ;;
  3)
   virsh list --all
  ;;
  4)
   exit
  ;; 
  esac
done



